﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace caufingHealth.Forms
{
    public partial class PatientForm : Form
    {
      /**  private List<MockPatientHistory> history = new List<MockPatientHistory>();
        private List<MockLabResults> labs = new List<MockLabResults>();**/
        private Imanager myManager;
        
        public enum MODES { REGISTER, VIEW }

        private const int _PINFO_ = 0;
        private const int _PVISIT_ = 1;
        private const int _PLAB_ = 2;

        private MODES currentMode;
        
        private int selectedRecordRow = -1;
        private int selectedLabRow = -1;

        public int patientID{
            get;
            private set;
        }
  
        public PatientForm()
        {
            InitializeComponent();
        
            txt_FirstName.KeyPress += KeyPressEvent;
            txt_LastName.KeyPress += KeyPressEvent;
            txt_MiddleInitial.KeyPress += KeyPressEvent;
            txt_Street.KeyPress += KeyPressEvent;
            txt_City.KeyPress += KeyPressEvent;
            txt_ZipCode.KeyPress += KeyPressEvent;
            btn_SaveChanges.Visible = false;

        }

        public PatientForm(MODES PatientMode) : this()
        {
            currentMode = PatientMode;
        }
            
        public PatientForm(Imanager _myManager)
            : this()
        {
            myManager = _myManager;
            currentMode = MODES.REGISTER;
            lbl_patient_id.Visible = false;
            txt_PatientID.Visible = false;
            btn_Lookup.Visible = false;
           // tbc_PatientInformation.TabPages.RemoveAt(1);
            
        }

        public PatientForm(PatientInformation.PatientRecord pinfo, Imanager _myManager)
            : this(_myManager)
        {      
            currentMode = MODES.VIEW;

            patientID = pinfo.PatientID;

            txt_FirstName.Text = pinfo.Name.FirstName;
            txt_MiddleInitial.Text = pinfo.Name.MI == null ? "" : pinfo.Name.MI;
            txt_LastName.Text = pinfo.Name.LastName;
            txt_Street.Text = pinfo.Address.Address;
            txt_City.Text = pinfo.Address.City;
            cb_State.SelectedIndex = cb_State.FindString(pinfo.Address.State);
            txt_ZipCode.Text = pinfo.Address.ZipCode;
            txt_DOB_Month.Text = pinfo.DateOfBirth.Month;
            txt_DOB_Day.Text = pinfo.DateOfBirth.Day;
            txt_DOB_Year.Text = pinfo.DateOfBirth.Year;
            txt_ContactNumber.Text = String.Format("{0}-{1}-{2}", pinfo.ContactNumber.AreaCode, pinfo.ContactNumber.LocalCode, pinfo.ContactNumber.ResidentialCode);
            txt_PatientID.Text = pinfo.PatientID.ToString();
        }

        private void btn_AddRecord_Click(object sender, EventArgs e)
        {
            VisitForm addVisit = new VisitForm(myManager.GetDoctorInformation());

            if (addVisit.ShowDialog() == DialogResult.OK)
            {
                myManager.AddNewPatientVisitRecord(patientID, addVisit.VisitRecord);
                DisplayPatientRecords();
            }
        }

        private void txt_FirstName_TextChanged(object sender, EventArgs e)
        {
            UpdateLabelName();
        }

        private void UpdateLabelName()
        {
            lbl_PatientsName.Text = String.Format("{0} {1} {2}", txt_FirstName.Text, txt_MiddleInitial.Text, txt_LastName.Text);
        }

        private void txt_MiddleInitial_TextChanged(object sender, EventArgs e)
        {
            UpdateLabelName();
        }

        private void txt_LastName_TextChanged(object sender, EventArgs e)
        {
            UpdateLabelName();
        }

        private void txt_FirstName_Validated(object sender, EventArgs e)
        {
            
        }

        private void btn_SaveChanges_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txt_FirstName.Text) &&
                !String.IsNullOrEmpty(txt_LastName.Text) &&
                !String.IsNullOrEmpty(txt_Street.Text) &&
                !String.IsNullOrEmpty(txt_City.Text) &&
                !String.IsNullOrEmpty(txt_ZipCode.Text) &&
                !String.IsNullOrEmpty(txt_DOB_Month.Text) &&
                !String.IsNullOrEmpty(txt_DOB_Day.Text) &&
                !String.IsNullOrEmpty(txt_DOB_Year.Text) &&
                !String.IsNullOrEmpty(txt_ContactNumber.Text))
            {

                switch (currentMode)
                {
                    case MODES.REGISTER:
                        PatientInformation.PatientRecord newRecord = new PatientInformation.PatientRecord();
                        newRecord.SetName(0, txt_FirstName.Text, txt_LastName.Text);
                        newRecord.SetAddress(int.Parse(txt_Street.Text.Substring(0, txt_Street.Text.IndexOf(" ")).Trim()), txt_Street.Text.Substring(txt_Street.Text.IndexOf(" ")).Trim(), txt_City.Text, (string)cb_State.SelectedItem, int.Parse(txt_ZipCode.Text.Trim()));
                        newRecord.SetDateOfBirth(int.Parse(txt_DOB_Month.Text), int.Parse(txt_DOB_Day.Text), int.Parse(txt_DOB_Year.Text));

                        string data = txt_ContactNumber.Text.Replace("(", "");
                        data = data.Replace(")", "");
                        data = data.Replace("-", "");
                        data = data.Replace(" ", "");
                        
                        newRecord.SetContactNumber(data);
                        if (myManager.AddPatientRecord(newRecord))
                            MessageBox.Show("Record Added Successfully");
                        else
                            MessageBox.Show("Record Creation failed");
                        this.Close();
                        break;
                    case MODES.VIEW:
                        MessageBox.Show("This Feature has not been implemented yet.");
                        break;
                }
            } 
        }

        private void txt_ContactNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar))
            {
                if (char.IsDigit(e.KeyChar))
                {
                    if (((TextBox)sender).Text.Length == 3)
                    {
                        ((TextBox)sender).Text += "-";
                        ((TextBox)sender).Select(((TextBox)sender).TextLength, 0);
                    }
                    else if (((TextBox)sender).Text.Length == 7)
                    {
                        ((TextBox)sender).Text += "-";
                        ((TextBox)sender).Select(((TextBox)sender).TextLength, 0);
                    }
                }
                else
                {
                    e.Handled = true;
                }
            }
            if (!btn_SaveChanges.Visible)
                btn_SaveChanges.Visible = true;
        }

        private void txt_ContactNumber_TextChanged(object sender, EventArgs e)
        {

        }

        private void txt_ContactNumber_Validating(object sender, CancelEventArgs e)
        {
            if (((TextBox)sender).TextLength < ((TextBox)sender).MaxLength)
                if (((TextBox)sender).TextLength != 0)
                {
                    MessageBox.Show("Invalid phone number");
                    ((TextBox)sender).Focus();
                }
        }

        private void txt_ZipCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            if (!btn_SaveChanges.Visible)
                btn_SaveChanges.Visible = true;
        }

        private void txt_ZipCode_Validating(object sender, CancelEventArgs e)
        {
            if (((TextBox)sender).TextLength < 5)
            {
                MessageBox.Show("Invalid ZipCode entered");
                ((TextBox)sender).Focus();
            }
        }

        private void txt_DOB_Month_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            if (!btn_SaveChanges.Visible)
                btn_SaveChanges.Visible = true;
        }

        private void txt_DOB_Day_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            if (!btn_SaveChanges.Visible)
                btn_SaveChanges.Visible = true;
        }

        private void txt_DOB_Year_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            if (!btn_SaveChanges.Visible)
                btn_SaveChanges.Visible = true;
        }

        private void txt_DOB_Month_Validating(object sender, CancelEventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(txt_DOB_Month.Text))
                if (int.Parse(((TextBox)sender).Text) < 1 || int.Parse(((TextBox)sender).Text) > 12)
                {
                    MessageBox.Show("The month must be between 1 and 12");
                    ((TextBox)sender).Focus();
                    ((TextBox)sender).SelectAll();
                }
        }

        private void txt_DOB_Day_Validating(object sender, CancelEventArgs e)
        {
            if (!String.IsNullOrWhiteSpace(txt_DOB_Day.Text))
                if (int.Parse(((TextBox)sender).Text) < 1 || int.Parse(((TextBox)sender).Text) > 31)
                {
                    MessageBox.Show("The month must be between 1 and 31");
                    ((TextBox)sender).Focus();
                    ((TextBox)sender).SelectAll();
                }
        }

        private void txt_DOB_Year_Validating(object sender, CancelEventArgs e)
        {
            if(!String.IsNullOrWhiteSpace(txt_DOB_Year.Text))
                if (int.Parse(((TextBox)sender).Text) < 1 || int.Parse(((TextBox)sender).Text) > 9999)
                {
                    MessageBox.Show("The month must be between 1 and 9999");
                    ((TextBox)sender).Focus();
                    ((TextBox)sender).SelectAll();
                }
        }

        private void KeyPressEvent(object sender, KeyPressEventArgs e)
        {
            if (!btn_SaveChanges.Visible)
                btn_SaveChanges.Visible = true;
        }

        private void tbc_PatientInformation_Selected(object sender, TabControlEventArgs e)
        {
           // getPatientVisitRecord
            switch (e.TabPageIndex)
            {
                case _PVISIT_:
                    DisplayPatientRecords();
                    break;
                case _PLAB_:
                    DisplayLabRecords();
                    break;
            }
        }

        private void DisplayPatientRecords()
        {
            PatientInformation.PatientRecord.PatientVisitRecord[] visits = myManager.GetPatientVisitRecord(patientID);
            selectedRecordRow = -1;
            dgv_History.DataSource = visits;
        }

        private void DisplayLabRecords()
        {
            long visitTime = long.Parse((string)(dgv_History.Rows[selectedRecordRow].Cells[7].EditedFormattedValue));
            PatientInformation.PatientRecord.PatientLabRecord[] labs = myManager.GetPatientLabRecord(visitTime, patientID);
            dgv_LabResults.DataSource = labs;
        }

        private void tbc_PatientInformation_Selecting(object sender, TabControlCancelEventArgs e)
        {
            switch (e.TabPageIndex)
            {
                case _PLAB_:
                    if (currentMode == MODES.REGISTER)
                        e.Cancel = true;

                    if (selectedRecordRow < 0)
                    {
                        e.Cancel = true;
                        MessageBox.Show("No visit record selected.", "Select visit record", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case _PVISIT_:
                    if (currentMode == MODES.REGISTER)
                        e.Cancel = true;
                    break;
            }
        }

        private void dataGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                if (((DataGridView)sender).Rows.Count > 1)
                {
                    DataGridViewRow row = ((DataGridView)sender).Rows[e.RowIndex];
                    bool isChecked = (bool)((row.Cells[e.ColumnIndex]).EditedFormattedValue);
                }
            }
        }

        private void dataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
                
            DataGridViewRow row = ((DataGridView)sender).Rows[e.RowIndex];
            bool isChecked = (bool)((row.Cells[0]).EditedFormattedValue);
            int i = 0;
            foreach (DataGridViewRow rowdata in ((DataGridView)sender).Rows)
            {
                if (((bool)rowdata.Cells[0].EditedFormattedValue) && i != e.RowIndex)
                    rowdata.Cells[0].Value = false;
                  
                i++;
            }

            if (isChecked)
            {
                if(((DataGridView)sender).Equals(dgv_History))
                    selectedRecordRow = e.RowIndex;
                if (((DataGridView)sender).Equals(dgv_LabResults))
                    selectedLabRow = e.RowIndex;
            }
        }

        private void patientVisitRecordBindingSource_CurrentChanged(object sender, EventArgs e)
        {

        }

        private void PatientForm_Load(object sender, EventArgs e)
        {

        }

        private void btn_UpdateRecord_Click(object sender, EventArgs e)
        {
            PatientInformation.PatientRecord.PatientVisitRecord record = new PatientInformation.PatientRecord.PatientVisitRecord();
            if (selectedRecordRow == -1)
            {
                MessageBox.Show("You have not selected a record to update.", "Please select a record.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                DataGridViewRow row = dgv_History.Rows[selectedRecordRow];
                record.VisitDate = new DateTime((long)row.Cells[7].Value);
                record.VisitDateLong = (long)row.Cells[7].Value;
                record.Symptoms = (string)row.Cells[2].EditedFormattedValue;
                record.Temperature = (string)row.Cells[3].EditedFormattedValue;
                record.Pulse = (string)row.Cells[4].EditedFormattedValue;
                record.BloodPressure1 = (string)row.Cells[5].EditedFormattedValue;
                record.BloodPressure2 = (string)row.Cells[6].EditedFormattedValue;
                record.Diagnosis = (string)row.Cells[8].EditedFormattedValue;
                record.DoctorID = int.Parse((string)row.Cells[9].EditedFormattedValue);

                VisitForm updateVisit = new VisitForm(VisitForm.MODES.UPDATE, record, myManager.GetDoctorInformation());

                if (updateVisit.ShowDialog() == DialogResult.OK)
                {
                    myManager.updatePatientVisitRecord(patientID, updateVisit.VisitRecord);
                    DisplayPatientRecords();
                }
            }
        }

        private void btn_DeleteRecord_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = dgv_History.Rows[selectedRecordRow];
            myManager.deletePatientVisitRecord(patientID, (long)row.Cells[7].Value);

            DisplayPatientRecords();
        }

        private void btn_lab_add_Click(object sender, EventArgs e)
        {
            LabTestForm addTest = new LabTestForm(myManager.GetAvailableTests(), myManager.GetDoctorInformation());
            if(addTest.ShowDialog(this) == DialogResult.OK)
            {
                DataGridViewRow row = dgv_History.Rows[selectedRecordRow];
                myManager.addPatientLabRecord(patientID, addTest.DoctorID, (long)row.Cells[7].Value, addTest.labID, addTest.labResult);
            }
            DisplayLabRecords();
        }

        private void btn_lab_delete_Click(object sender, EventArgs e)
        {

        }

        private void btn_UpdateResult_Click(object sender, EventArgs e)
        {
            DataGridViewRow labRow = dgv_LabResults.Rows[selectedLabRow];
            DataGridViewRow recordRow = dgv_History.Rows[selectedRecordRow];
           
            LabTestForm addTest = new LabTestForm((int)recordRow.Cells[9].Value, (string)labRow.Cells[2].EditedFormattedValue, (string)labRow.Cells[3].EditedFormattedValue, myManager.GetAvailableTests(), myManager.GetDoctorInformation());

            if (addTest.ShowDialog(this) == DialogResult.OK)
            {
                myManager.updatePatientLabRecord(patientID, addTest.DoctorID, (long)recordRow.Cells[7].Value, addTest.labID, addTest.labResult);
            }
            DisplayLabRecords();
        }
    }
}
